import { useState, useEffect } from "react";
import {
  Button,
  Space,
  Tag,
  Input,
  message,
  Empty,
  Divider,
  FloatButton,
  Tooltip,
} from "antd";
import {
  StarOutlined,
  StarFilled,
  LinkOutlined,
  CheckOutlined,
  EditOutlined,
  SaveOutlined,
  ArrowLeftOutlined,
  VerticalAlignTopOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import type { Article } from "../types";
import {
  markAsRead,
  markAsUnread,
  toggleFavorite,
  updateNote,
} from "../services/article";

const { TextArea } = Input;

interface ArticleReaderProps {
  article: Article | null;
  onRefresh: () => void;
  onBack?: () => void;
  isFullScreen?: boolean;
}

export default function ArticleReader({
  article,
  onRefresh,
  onBack,
  isFullScreen = false,
}: ArticleReaderProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [note, setNote] = useState("");

  useEffect(() => {
    if (article) {
      setNote(article.user_note || "");
      setIsEditing(false);
      if (!article.is_read) {
        markAsRead(article.id).catch(() => {});
      }
    }
  }, [article]);

  const handleMarkAsRead = async () => {
    if (!article) return;
    try {
      await markAsRead(article.id);
      onRefresh();
    } catch {
      message.error("操作失败");
    }
  };

  const handleMarkAsUnread = async () => {
    if (!article) return;
    try {
      await markAsUnread(article.id);
      message.success("已标记为未读");
      onRefresh();
    } catch {
      message.error("操作失败");
    }
  };

  const handleToggleFavorite = async () => {
    if (!article) return;
    try {
      await toggleFavorite(article.id);
      message.success(article.is_starred ? "已取消收藏" : "已收藏");
      onRefresh();
    } catch {
      message.error("操作失败");
    }
  };

  const handleSaveNote = async () => {
    if (!article) return;
    try {
      await updateNote(article.id, note);
      message.success("笔记已保存");
      setIsEditing(false);
      onRefresh();
    } catch {
      message.error("保存失败");
    }
  };

  if (!article) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: "100%",
          flexDirection: "column",
        }}
      >
        <Empty
          description={
            <span style={{ fontSize: "16px", color: "#8c8c8c" }}>
              请从左侧选择文章开始阅读
            </span>
          }
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </div>
    );
  }

  // 全屏模式样式
  const containerStyle = isFullScreen
    ? {
        maxWidth: "1200px",
        margin: "0 auto",
        padding: "40px 80px",
        height: "100%",
        overflowY: "auto" as const,
        background: "#fff",
      }
    : {
        maxWidth: "900px",
        margin: "0 auto",
        padding: "32px 40px",
        height: "100%",
        overflowY: "auto" as const,
      };

  return (
    <div style={containerStyle}>
      {/* 文章标题 */}
      <h1
        style={{
          fontSize: isFullScreen ? "32px" : "28px",
          fontWeight: 700,
          marginBottom: "20px",
          lineHeight: "1.5",
          color: "#1a1a1a",
          letterSpacing: "-0.5px",
        }}
      >
        {article.title}
      </h1>

      {/* 文章元信息 - 优化布局,避免覆盖 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: "16px",
          marginBottom: "24px",
          paddingBottom: "20px",
          borderBottom: "1px solid #e8e8e8",
        }}
      >
        <Space size="large" style={{ fontSize: "14px", color: "#8c8c8c" }}>
          <span>
            📅 {dayjs(article.published_at).format("YYYY-MM-DD HH:mm")}
          </span>
          {article.author && <span>✍️ {article.author}</span>}
        </Space>

        {/* 操作按钮 - 移到右侧,避免覆盖作者名 */}
        <Space size="small">
          <Tooltip title={article.is_starred ? "取消收藏" : "收藏"}>
            <Button
              icon={article.is_starred ? <StarFilled /> : <StarOutlined />}
              onClick={handleToggleFavorite}
              type={article.is_starred ? "primary" : "default"}
            />
          </Tooltip>
          <Tooltip title={article.is_read ? "标记未读" : "标记已读"}>
            <Button
              icon={<CheckOutlined />}
              onClick={article.is_read ? handleMarkAsUnread : handleMarkAsRead}
            />
          </Tooltip>
          <Tooltip title="查看原文">
            <Button
              icon={<LinkOutlined />}
              onClick={() => window.open(article.link, "_blank")}
            />
          </Tooltip>
        </Space>
      </div>
      {/* AI 摘要卡片 */}
      {article.ai_summary && (
        <div
          style={{
            background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
            padding: "24px 28px",
            borderRadius: "12px",
            marginBottom: "32px",
            boxShadow: "0 4px 16px rgba(102, 126, 234, 0.2)",
          }}
        >
          <div
            style={{
              fontSize: "15px",
              fontWeight: 600,
              marginBottom: "12px",
              color: "#fff",
              display: "flex",
              alignItems: "center",
              gap: "8px",
            }}
          >
            🤖 AI 摘要
          </div>
          <div
            style={{
              fontSize: "15px",
              lineHeight: "1.8",
              color: "#fff",
              opacity: 0.95,
            }}
          >
            {article.ai_summary}
          </div>
          {article.ai_tags && article.ai_tags.length > 0 && (
            <div style={{ marginTop: "16px" }}>
              {article.ai_tags.map((tag) => (
                <Tag
                  key={tag}
                  style={{
                    background: "rgba(255, 255, 255, 0.25)",
                    color: "#fff",
                    fontSize: "13px",
                    padding: "4px 12px",
                    marginRight: "8px",
                    marginBottom: "8px",
                    border: "1px solid rgba(255, 255, 255, 0.3)",
                  }}
                >
                  {tag}
                </Tag>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 文章正文 - 使用优化的样式类 */}
      <div
        className="article-content"
        style={{
          fontSize: "16px",
          lineHeight: "1.8",
          marginBottom: "48px",
          color: "#333",
        }}
        dangerouslySetInnerHTML={{ __html: article.content }}
      />

      <Divider style={{ margin: "48px 0 32px 0" }} />

      {/* 笔记区域 */}
      <div style={{ marginBottom: "80px" }}>
        <div
          style={{
            fontSize: "18px",
            fontWeight: 600,
            marginBottom: "16px",
            color: "#262626",
          }}
        >
          📝 我的笔记
          {!isEditing && (
            <Button
              size="middle"
              icon={<EditOutlined />}
              onClick={() => setIsEditing(true)}
              style={{ marginLeft: "12px" }}
            >
              编辑
            </Button>
          )}
        </div>
        {isEditing ? (
          <>
            <TextArea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="在这里记录你的想法..."
              rows={8}
              style={{
                marginBottom: "12px",
                fontSize: "15px",
                borderRadius: "8px",
              }}
            />
            <Space>
              <Button
                type="primary"
                size="large"
                icon={<SaveOutlined />}
                onClick={handleSaveNote}
              >
                保存
              </Button>
              <Button size="large" onClick={() => setIsEditing(false)}>
                取消
              </Button>
            </Space>
          </>
        ) : (
          <div
            style={{
              padding: "20px",
              background: "#fafafa",
              borderRadius: "8px",
              fontSize: "15px",
              lineHeight: "1.6",
              color: "#595959",
              minHeight: "120px",
            }}
          >
            {note || "暂无笔记,点击编辑按钮开始记录..."}
          </div>
        )}
      </div>

      {/* 浮动工具栏 - 始终显示,固定在右下角 */}
      {isFullScreen && (
        <>
          {/* 返回列表和返回顶部 - 小按钮组 */}
          <FloatButton.Group style={{ right: 450, bottom: 24 }}>
            <FloatButton
              icon={<ArrowLeftOutlined />}
              tooltip="返回列表"
              onClick={onBack}
              type="primary"
            />
            <FloatButton
              icon={<VerticalAlignTopOutlined />}
              tooltip="返回顶部"
              onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
            />
          </FloatButton.Group>
        </>
      )}
    </div>
  );
}
